package org.yh.util.httpUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HTTPS {
    private static final String SYS_VULLN_URL_JSON = "https://47.100.223.104:17803/createaccount?requestid=1&sa=ql87011&sapass=123456&account=0&password=123456&name=张三&mainaccount=";

    public static String gb2312ToUtf8(String str) {
        String urlEncode = "";
        try {
            urlEncode = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return urlEncode;
    }

    public static void main(String[] args) {
        //String xml = HTTPS.sendHtpps(SYS_VULLN_URL_JSON);
        //System.out.println("结果：" + xml);
        String xml2 = "<root>\n" +
                "<Result>\n" +
                "<Error>\n" +
                "<Code>1</Code>\n" +
                "<Message>没有可用主账号</Message>\n" +
                "</Error>\n" +
                "<RequestID>1</RequestID>\n" +
                "</Result>\n" +
                "</root>";
        //System.out.println("结果2：" + xml2);
        String z = "��֧�ִ˹���";
        String s = HTTPS.gb2312ToUtf8(z);
        log.info("gb2312转utf-8" + s);
    }

    public static Map<String, String> StrXmlTOMap(String strXml) throws Exception {

        Map<String, String> map = new HashMap<String, String>();
        Document docment = DocumentHelper.parseText(strXml);
        Element root = docment.getRootElement();
        List<Element> list = root.elements();
        for (Element ele : list) {
            map.put(ele.getName(), ele.getText());
            System.out.println(ele.getName() + "   " + ele.getText());
        }
        return map;
    }

    public static String sendHtpps(String openIdSessionkeyUrl) {
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn;
        try {
            trustAllHosts();
            URL realUrl = new URL(openIdSessionkeyUrl);
            // 通过请求地址判断请求类型(http或者是https)
            if (realUrl.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            // out.print(a);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            result = IOUtils.toString(conn.getInputStream(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

}